/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Principal;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
 *
 * @author Borja
 */
@WebServlet(name = "Pedidos", urlPatterns = {"/Pedidos"})
public class Pedidos extends HttpServlet {
   
   @Resource(name = "jdbc/Tienda_bfernandezo_asanchezoliv")
    private DataSource ds;
    private String contenido;
    private Cesta cesta = Cesta.getInstancia();
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            char comillas = '"';
out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
            out.println("<title>En ca' Paqui</title>");
            out.println("<link href='styles/styles.css' rel='stylesheet' type='text/css'>");
            out.println("<script src='scripts/jquery-1.7.js' type='text/javascript'></script>");
            out.println("<script src='scripts/general.js' type='text/javascript'></script>  ");
            out.println("        <script>");
            out.println("$(document).ready(function() {");
            out.println("        $('#texto').bind('keypress', function(event){");
            out.println("        var opcion = $('#tipo option:selected').html();");
            out.println("        if (opcion == 'Precio') {");
            out.println("            if ( (  (event.keyCode < 48) || (event.keyCode > 57)) && (event.keyCode != 13) && (event.keyCode != 46))");
            out.println("                return false;");
            out.println("        }");
            out.println("    });");
            out.println("});");
            out.println("function mostrarOperador(){");
            out.println("    var opcion = $('#tipo option:selected').html();");
            out.println("        if (opcion == 'Precio') ");
            out.println("            $('#operador').css('display','initial');");
            out.println("        else");
            out.println("            $('#operador').css('display','none');");
            out.println("        }");
            out.println("</script>");
            out.println("  </head>");
            out.println("  <body>");
            out.println("          <a id='titulo' href='/Tienda_bfernandezo_asanchezoliv'><h1 id='titulo'>Tienda virtual "+comillas+"En ca' Paqui"+comillas+"</h1></a>");
            out.println("          <div class='cesta'>");
            out.println(" <span><a href='cesta.jsp' id='txtNegro'> Cesta: </span><span><b>"+cesta.getTamanoCesta()+"</b></span><span> artículo/s | </span></a> <a href='Login'> Loguearse </a>");
            out.println("          </div>");
            out.println("          <div class='superior'>");
            out.println("              <div class='categoria'>");
            out.println("                  <b>Categoría</b>");
            out.println("                  <form name='Categoria' action='categoria'>        ");
            out.println("                      <p><a id ='sangria' href='index?t=1&categoria=1'>Alimentación</a> </p>");
            out.println("                      <p><a id ='sangria' href='index?t=1&categoria=2'>Droguería</a> </p>              ");
            out.println("                      <p><a id ='sangria' href='index?t=1&categoria=3'>Prensa</a> </p>               ");
            out.println("                      <p><a id ='sangria' href='index?t=1&categoria=4'>Herramientas</a>  </p>    ");
            out.println("                  </form>");
            out.println("              </div>");
            out.println("              ");
            out.println("              <div class='busqueda'>  ");
            out.println("                  <form name='Busqueda' action='index' method='get' class='formBusqueda'>");    
            out.println("                      <b>Busqueda</b> ");
            out.println("                      <select id='tipo' name='t' size='1' onchange="+comillas+"$('#texto').attr('value','');mostrarOperador();"+comillas+">");
            out.println("                          <option name='t' value='2'>Nombre</option>");
            out.println("                          <option name='t' value='3'>Precio</option>");
            out.println("                       </select>");
            out.println("                       <select class='operador' id='operador' name='operador' size='1'>");
            out.println("                           <option value='1'>menor que</option>");
            out.println("                           <option value='2'>menor igual que</option>");
            out.println("                           <option value='3'>igual que</option>");
            out.println("                           <option value='4'>mayor o igual que</option>");
            out.println("                           <option value='5'>mayor que</option>");                            
            out.println("                       </select>");
            out.println("                       <input id='texto'type='text' name='texto' value='' />");
            out.println("                       <input type='submit' value='Ir' name='Ir' />");
            out.println("                  </form>");out.println("               </div>");
            out.println("           </div>");
            out.println("            <div class='contenido'>");
            out.println("               <h2>Gracias por su pedido. Recuerde que puede recogerlo pasadas 24h desde su realización. Esperamos verle pronto. <br /> <br />Paqui.");
            out.println("        </div>");
            out.println("</body>");
            out.println("</html>");
            
            
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id =0;
        try{
            id = Integer.parseInt(request.getParameter("id"));
            Tienda.getInstancia(ds).marcarEntregado(id);
            response.sendRedirect("/Tienda_bfernandezo_asanchezoliv/admin.jsp");
            
        }catch(Exception e){}
        try{
            contenido = "";
            ArrayList<Producto> productos = cesta.getProductos();
            ArrayList<Integer> cantidad = cesta.getCantidad();
            for (Producto producto:productos){
            
            }            
        }catch(Exception e){}
        if (id == 0)
            getServletConfig().getServletContext().getRequestDispatcher(
        "/cesta.jsp").forward(request,response);     
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try{
            Tienda tienda = Tienda.getInstancia(ds);
            String nombre = "";
            try{
               nombre = request.getParameter("nombre");
            }catch(Exception e1){nombre = "";}
            if (nombre == "")
                response.sendRedirect("cesta.jsp?eN=2");
            else               
                tienda.realizarPedido(request.getParameter("nombre"));
        }catch(Exception e){

        }

        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
